package com.kakarote.examine.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.kakarote.core.common.cache.CrmCacheKey;
import com.kakarote.core.entity.UserInfo;
import com.kakarote.core.feign.admin.service.AdminService;
import com.kakarote.core.feign.examine.entity.ExamineDataSaveBO;
import com.kakarote.core.feign.examine.entity.ExamineFlowVO;
import com.kakarote.core.servlet.ApplicationContextHolder;
import com.kakarote.core.servlet.BaseServiceImpl;
import com.kakarote.core.utils.BaseUtil;
import com.kakarote.core.utils.UserUtil;
import com.kakarote.examine.constant.ExamineEnum;
import com.kakarote.examine.constant.ExamineStatusEnum;
import com.kakarote.examine.constant.ExamineTypeEnum;
import com.kakarote.examine.entity.PO.*;
import com.kakarote.examine.mapper.ExamineFlowMemberComponentMapper;
import com.kakarote.examine.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: admin
 * @version: v1.0
 * @date:2023/5/8
 */
@Service("memberComponentService")
public class ExamineFlowMemberComponentServiceImpl extends BaseServiceImpl<ExamineFlowMemberComponentMapper, ExamineFlowMemberComponent> implements IExamineFlowMemberComponentService, ExamineTypeService {

    @Autowired
    private AdminService adminService;

    @Autowired
    private IExamineRecordService examineRecordService;

    @Autowired
    private IExamineFlowFinalService examineFlowFinalService;

    @Autowired
    private IExamineFlowFinalOptionalService examineFlowFinalOptionalService;

    @Autowired
    private IExamineRecordLogService examineRecordLogService;

    /**
     * 保存额外的审批流程data对象
     *
     * @param dataSaveBO data
     * @param flowId     审批流程ID
     * @param batchId
     */
    @Override
    public void saveExamineFlowData(ExamineDataSaveBO dataSaveBO, Long flowId, String batchId) {
        ExamineFlowMemberComponent examinFlow = new ExamineFlowMemberComponent();
        examinFlow.setFlowId(flowId);
        examinFlow.setFieldId(dataSaveBO.getFieldId());
        examinFlow.setType(dataSaveBO.getType());
        examinFlow.setParentLevel(dataSaveBO.getParentLevel());
        examinFlow.setBatchId(batchId);
        examinFlow.setFieldName(dataSaveBO.getFieldName());
        save(examinFlow);
    }


    /**
     * 通过batchId查询所有flow关联对象
     *
     * @param map     缓存对象
     * @param batchId batchId
     */
    @Override
    public void queryFlowListByBatchId(Map<String, Object> map, String batchId) {
        List<ExamineFlowMemberComponent> flowMemberComponentList = lambdaQuery().eq(ExamineFlowMemberComponent::getBatchId, batchId).list();
        Map<Long, List<ExamineFlowMemberComponent>> collect = flowMemberComponentList.stream().collect(Collectors.groupingBy(ExamineFlowMemberComponent::getFlowId));
        map.put(ExamineTypeEnum.MEMBER_COMPONENT.getServerName(), collect);
    }

    /**
     * 查询详情页需要的审批详情
     *
     * @param examineFlow 当前审批流程
     * @param map         缓存的map
     * @param allUserList
     * @param ownerUserId
     * @return data
     */
    @Override
    public ExamineFlowVO createFlowInfo(ExamineFlow examineFlow, Map<String, Object> map, List<UserInfo> allUserList, Long ownerUserId) {
        Map<Long, List<ExamineFlowMemberComponent>> collect = (Map<Long, List<ExamineFlowMemberComponent>>) map.get(ExamineTypeEnum.MEMBER_COMPONENT.getServerName());
        List<ExamineFlowMemberComponent> flowMemberComponentList = collect.get(examineFlow.getFlowId());
        if (flowMemberComponentList == null || flowMemberComponentList.size() == 0) {
            return null;
        }
        ExamineFlowMemberComponent flowMemberComponent = flowMemberComponentList.get(0);
        ExamineFlowVO examineFlowVO = new ExamineFlowVO();
        examineFlowVO.setType(flowMemberComponent.getType());
        examineFlowVO.setName(examineFlow.getName());
        examineFlowVO.setExamineType(examineFlow.getExamineType());
        examineFlowVO.setFlowId(examineFlow.getFlowId());
        examineFlowVO.setParentLevel(flowMemberComponent.getParentLevel());
        examineFlowVO.setExamineErrorHandling(examineFlow.getExamineErrorHandling());
        examineFlowVO.setFieldId(flowMemberComponent.getFieldId());
        examineFlowVO.setFieldName(flowMemberComponent.getFieldName());

        examineFlowVO.setUserList(new ArrayList<>());
        return examineFlowVO;
    }


    private List<Long> queryUser(List<UserInfo> userInfoList, Long userId) {
        List<Long> idList = new ArrayList<>();
        //管理员没有上级
        if (userId == null || userId == 0 || userInfoList.isEmpty()) {
            idList.add(userId);
            return idList;
        }
        for (UserInfo userInfo : userInfoList) {
            if (userId.equals(userInfo.getUserId())) {
                idList.add(userId);
                if (userInfo.getParentId() == null || userInfo.getParentId() == 0) {
                    return idList;
                }
                idList.addAll(queryUser(userInfoList, userInfo.getParentId()));
            }
        }
        return idList;
    }

    /**
     * 处理当前节点
     *
     * @param examineFlow 当前处理节点
     * @param recordId    审核记录ID
     * @param data        特殊处理所需数据(具体看实现类)
     * @param examine     审核对象
     * @param init        是否初始化
     * @return data
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject disposeFlow(ExamineFlow examineFlow, Long recordId, Object data, Examine examine, boolean init) {
        ExamineFlowMemberComponent flowMemberComponent = lambdaQuery().eq(ExamineFlowMemberComponent::getFlowId, examineFlow.getFlowId()).one();

        ExamineRecord examineRecord = examineRecordService.getById(recordId);

        examineFlow.setExamineId(examineRecord.getExamineId());

        ExamineFlowFinal examineFlowFinal = examineFlowFinalService.lambdaQuery().eq(ExamineFlowFinal::getFlowId, examineFlow.getFlowId())
                .eq(ExamineFlowFinal::getRecordId, recordId).one();
        if (examineFlowFinal == null) {

            Integer maxSort = examineFlowFinalService.getMaxSort(recordId, examineRecord.getExamineId());
            examineFlowFinal = new ExamineFlowFinal();
            examineFlowFinal.setName(examineFlow.getName());
            examineFlowFinal.setExamineType(examineFlow.getExamineType());
            examineFlowFinal.setFlowId(examineFlow.getFlowId());
            examineFlowFinal.setExamineErrorHandling(examineFlow.getExamineErrorHandling());
            examineFlowFinal.setCreateTime(new Date());
            examineFlowFinal.setCreateUserId(UserUtil.getUserId());
            examineFlowFinal.setExamineId(examineRecord.getExamineId());
            examineFlowFinal.setRecordId(recordId);
            examineFlowFinal.setType(flowMemberComponent.getType());
            examineFlowFinal.setSort(maxSort + 1);
            examineFlowFinalService.save(examineFlowFinal);
        }

        ExamineModuleService moduleService = ApplicationContextHolder.getBean(ExamineEnum.parseModule(examineRecord.getLabel()).getServerName());
        String userIds = "";

        if (init) {
            Map<String, Object> user = (Map<String, Object>) data;
            Object value = user.get(flowMemberComponent.getFieldName());
            if (ObjectUtil.isNotEmpty(value)) {
                userIds = value.toString();
            }
        } else {
            Map<String, Object> memberComponentMap = moduleService.getMemberComponentMap(flowMemberComponent.getFieldName(), examineRecord.getLabel(), examineRecord.getTypeId(), recordId);

            if (memberComponentMap.containsKey(flowMemberComponent.getFieldName())) {
                Object value = memberComponentMap.get(flowMemberComponent.getFieldName());
                if (ObjectUtil.isNotEmpty(value)) {
                    if (value instanceof List) {
                        JSONArray list = JSONUtil.parseArray(value);
                        //获取userId,拼接,
                        userIds = list.stream().map(e -> JSONUtil.parseObj(e).get("userId").toString()).collect(Collectors.joining(StrUtil.COMMA));

                    } else if (value instanceof String) {
                        userIds = value.toString();
                    }
                }
            }
        }


        List<Long> userIdList = StrUtil.splitTrim(userIds, StrUtil.COMMA).stream().map(Long::valueOf).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(flowMemberComponent.getParentLevel())) {
            List<UserInfo> allUserList = adminService.queryUserInfoList().getData();
            List<Long> parentUserIds = new ArrayList<>();
            for (Long userId : userIdList) {
                for (UserInfo userInfo : allUserList) {
                    if (Objects.equals(userInfo.getUserId(), userId)) {

                        if (userInfo.getParentId() != null && userInfo.getParentId() != 0) {
                            List<Long> longList = queryUser(allUserList, userInfo.getParentId());
                            if (flowMemberComponent.getParentLevel() <= longList.size()) {
                                parentUserIds.add(longList.get(flowMemberComponent.getParentLevel() - 1));
                            }
                        }
                    }
                }
            }
            userIdList = parentUserIds;
        }

        List<ExamineFlowFinalOptional> flowFinalOptionals = examineFlowFinalOptionalService.lambdaQuery().eq(ExamineFlowFinalOptional::getRecordId, recordId)
                .eq(ExamineFlowFinalOptional::getFlowId, examineFlow.getFlowId()).list();
        if (flowFinalOptionals == null || flowFinalOptionals.size() == 0) {
            flowFinalOptionals = castFlowOptionalUser(userIdList, examineFlow.getFlowId(), recordId, flowMemberComponent.getType());
            examineFlowFinalOptionalService.saveBatch(flowFinalOptionals);
        }

        String batchId = IdUtil.simpleUUID();
        List<ExamineRecordLog> recordLogs = new ArrayList<>();
        LocalDateTime now = LocalDateTimeUtil.now();
        for (ExamineFlowFinalOptional examineFlowFinalUser : flowFinalOptionals) {
            ExamineRecordLog examineRecordLog = new ExamineRecordLog();
            examineRecordLog.setLogId(BaseUtil.getNextId());
            examineRecordLog.setType(examineFlowFinal.getType());
            examineRecordLog.setCreateTime(now);
            examineRecordLog.setExamineTime(now);
            examineRecordLog.setUpdateTime(null);
            examineRecordLog.setCreateUserId(UserUtil.getUserId());
            examineRecordLog.setExamineId(examineFlowFinal.getExamineId());
            examineRecordLog.setExamineRoleId(0L);
            //   在这块判断审核人状态，是否有效等
            examineRecordLog.setExamineUserId(examineFlowFinalUser.getUserId());
            if (examineFlowFinal.getType() == 1) {
                if (flowFinalOptionals.indexOf(examineFlowFinalUser) == 0) {
                    examineRecordLog.setExamineStatus(ExamineStatusEnum.UNDERWAY.getStatus());
                } else {
                    examineRecordLog.setExamineStatus(ExamineStatusEnum.AWAIT.getStatus());
                }
            } else {
                examineRecordLog.setExamineStatus(ExamineStatusEnum.UNDERWAY.getStatus());
            }
            if (ObjectUtil.isNotNull(examineFlowFinalUser.getUserId())) {
                BaseUtil.getRedis().del(CrmCacheKey.CRM_BACKLOG_NUM_CACHE_KEY + examineFlowFinalUser.getUserId().toString());
            }
            examineRecordLog.setFlowId(examineFlowFinal.getFlowId());
            examineRecordLog.setRecordId(recordId);
            examineRecordLog.setSort(examineFlowFinalUser.getSort());
            examineRecordLog.setBatchId(batchId);
            recordLogs.add(examineRecordLog);
        }
        examineRecordLogService.saveBatch(recordLogs);
        return ExamineTypeService.super.disposeFlow(examineFlow, recordId, data, examine, init);
    }

}
